package org.thirdHero.db.service;

import com.github.pagehelper.PageHelper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.thirdHero.db.dao.SysUserMapper;
import org.thirdHero.db.domain.SysRole;
import org.thirdHero.db.domain.SysUser;
import org.thirdHero.db.domain.SysUserExample;
import org.thirdHero.db.vo.SysUserVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class SysUserService implements UserDetailsService {
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysRoleService sysRoleService;


    public List<SysUserVo> querySysUser(SysUserVo litemallSysUserVo,Integer page,Integer limit){
        PageHelper.startPage(page,limit);
        return this.sysUserMapper.querySysUserVo(litemallSysUserVo);
    }
    public SysUser findById(String adminId){
        return this.sysUserMapper.selectByPrimaryKey(adminId);
    }
    public List<SysUser> findSysUser(String userName){
        SysUserExample example = new SysUserExample();
        example.createCriteria().andAccountEqualTo(userName);
        return sysUserMapper.selectByExample(example);
    }
    public void saveSysUser(SysUser sysUser){
        this.sysUserMapper.insert(sysUser);
    }
    public void deleteSysUser(String id){
        this.sysUserMapper.deleteByPrimaryKey(id);
    }
    public void setStatus(Integer userId,Integer status){
        this.sysUserMapper.setStatus(userId,status);
    }
    public void editSysUser(SysUser litemallSysUser){
        this.sysUserMapper.updateByPrimaryKeySelective(litemallSysUser);
    }

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        SysUserExample example = new SysUserExample();
        example.createCriteria().andAccountEqualTo(userName);
        List<SysUser> sysUsers = sysUserMapper.selectByExample(example);
        if(null != sysUsers && sysUsers.size()>0){
            SysUser sysUser = sysUsers.get(0);
            String roleId = sysUser.getRoleId();
            List<Integer> roleIds = new ArrayList<>();
            roleIds.add(Integer.parseInt(roleId));
            List<SysRole> sysRole = sysRoleService.queryByRoles(roleIds);
            sysUser.setAuthorities(sysRole);
            sysUser.setPassword(sysUser.getPassword()+"-"+sysUser.getSalt());
            return sysUser;
        }
        return null;
    }
}
